import gradio as gr
import numpy as np
from PIL import Image
import pickle
with open('best_knn_model.pkl', 'rb') as f:
    model = pickle.load(f)

# 定义预测函数
def predict(my_dict):
    a = my_dict['composite']
    a = np.array(a)
    a = a[:, :, 3]
    a = a / 255
    b = Image.fromarray(a, 'L')
    c = b.resize((8, 8))
    raveled_vector = np.array(c).ravel()
    
    # 使用加载的模型进行预测
    prediction = model.predict([raveled_vector])
    
    # 返回预测结果
    return int(prediction[0])

# 创建 Gradio 界面
iface = gr.Interface(
    fn=predict,  # 设置要调用的预测函数
    inputs=gr.Sketchpad(),  # 创建手写板
    outputs=gr.Label(num_top_classes=1),
    title="knn手写数字识别",  # 设置界面的标题
    description="knn预测手写数字"  # 设置界面的描述
)

iface.launch(share=True)